UI 開發人員經常需要在螢幕上顯示和隱藏內容。但在屏幕上快速彈入或彈出元素可能會讓使用者感到不適。所以使用不透明動畫淡入和淡出元素以創造流暢的體驗,總共有以下四個步驟
Container(
  width: 200.0,
  height: 200.0,
  color: Colors.green,
)
StatefulWidget 是一個創建 State 物件的class。 State 物件包含有關應用程式的一些數據,並提供了一種更新該數據的方法。簡單來說,StatefulWidget 會不斷更新,因此動畫很常使用到StatefulWidget
// The StatefulWidget's job is to take data and create a State class.
// In this case, the widget takes a title, and creates a _MyHomePageState.
class MyHomePage extends StatefulWidget {
  final String title;
  const MyHomePage({
    super.key,
    required this.title,
  });
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}
// The State class is responsible for two things: holding some data you can
// update and building the UI using that data.
class _MyHomePageState extends State<MyHomePage> {
  // Whether the green box should be visible.
  bool _visible = true;
  @override
  Widget build(BuildContext context) {
    // The green box goes here with some other Widgets.
  }
}
現在已經有了一些數據來確定綠色框是否應該可見,您需要一種方法來更新這些數據。在範例中,如果該框可見則將其隱藏,如果該框被隱藏則顯示它。使用 setState() 配合布林值操作,它是 State 類的一個方法。這告訴 Flutter 重建widget。
FloatingActionButton(
  onPressed: () {
    // Call setState. This tells Flutter to rebuild the
    // UI with the changes.
    setState(() {
      _visible = !_visible;
    });
  },
  tooltip: 'Toggle Opacity',
  child: const Icon(Icons.flip),
)
使用AnimatedOpacity widget淡入或淡出box,AnimatedOpacity widget需要三個參數:
AnimatedOpacity(
  // If the widget is visible, animate to 0.0 (invisible).
  // If the widget is hidden, animate to 1.0 (fully visible).
  opacity: _visible ? 1.0 : 0.0,
  duration: const Duration(milliseconds: 500),
  // The green box must be a child of the AnimatedOpacity widget.
  child: Container(
    width: 200.0,
    height: 200.0,
    color: Colors.green,
  ),
)

參考資料:
https://docs.flutter.dev/cookbook/animation/opacity-animation